package org.example.project.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.bean.Book;
import org.example.config.JwtConfig;
import org.example.mapper.BookMapper;
import org.example.project.bookstore.service.BookService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Auther:Liu
 * @Testname:BookServiceImpl
 * @Date:2025/8/18 10:08
 */
@Service
@Slf4j
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Resource
    private BookMapper bookMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取低价书籍
     *
     * @param number
     * @return
     */
    @Cacheable(cacheNames = "getLowerBook", key = "#number")
    public JsonResult getLowerBook(int number) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.last("limit " + number);
        wrapper.orderByAsc("price");
        return ResultTool.success(list(wrapper));
    }

    /**
     * 获取最新上架书籍
     *
     * @param number
     * @return
     */
    @Cacheable(cacheNames = "getNewBook", key = "#number")
    public JsonResult getNewBook(int number) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.last("limit " + number);
        wrapper.orderByDesc("create_time");
        return ResultTool.success(list(wrapper));
    }

    /**
     * 查询所有新书
     *
     * @param page
     * @return
     */
    @Cacheable(cacheNames = "getAllNewBook", key = "#page+'.'+#token")
    public JsonResult getAllNewBook(int page, String token) {
        IPage<Book> iPage = new Page<>(page, 10);
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.last("and create_time >(select DATE_ADD(now(),INTERVAL -3 day)) order by create_time desc");
        List<Book> list = list(wrapper);
//        List<Book> books = checkExistsCart(list, token);
        iPage.setRecords(list);
        return ResultTool.success(iPage);
    }

    /**
     * 根据分类名查书
     *
     * @param page
     * @param categoryId
     * @return
     */
    @Cacheable(cacheNames = "findBookByCateGory", key = "#page+'.'+#categoryId+'.'+#token")
    public JsonResult findBookByCateGory(int page, String categoryId, String token) {
        IPage<Book> iPage = new Page<>(page, 10);
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryId);
        List<Book> list = list(iPage, wrapper);
//        List<Book> books = checkExistsCart(list, token);
        //只在Redis中存放公共数据,在Controller中设置私有属性
//        log.info("books: {}", books);
        iPage.setRecords(list);
        return ResultTool.success(iPage);
    }

    /**
     * 一级搜索框,模糊查询图书
     *
     * @param page
     * @param bookName
     * @return
     */
    @Cacheable(cacheNames = "findBookByName", key = "#page+'.'+#bookName+'.'+#token")
    public JsonResult findBookByName(int page, String bookName, String token) {
        IPage<Book> iPage = new Page<>(page, 10);
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.like("name", bookName);
        List<Book> list = list(iPage, wrapper);
//        List<Book> books = checkExistsCart(list, token);
        iPage.setRecords(list);
        return ResultTool.success(iPage);
    }

    /**
     * 二级搜索,分类基础查询价格
     *
     * @param page
     * @param categoryId
     * @param bookName
     * @return
     */
    @Cacheable(cacheNames = "findBookByCategoryAndPrice", key = "#page+'.'+#categoryId+'.'+#bookName+'.'+#token")
    public JsonResult findBookByCategoryAndPrice(int page, String categoryId, String bookName, String token) {
        IPage<Book> iPage = new Page<>(page, 10);
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", categoryId);
        wrapper.like("name", bookName);
        List<Book> list = list(iPage, wrapper);
//        List<Book> books = checkExistsCart(list, token);
        iPage.setRecords(list);
        return ResultTool.success(iPage);
    }

    /**
     * 二级搜索,双模糊
     *
     * @param page
     * @param bookName
     * @param bookName2
     * @return
     */
    @Cacheable(cacheNames = "findBookByNames", key = "#page+'.'+#bookName+'.'+#bookName2+'.'+#token")
    public JsonResult findBookByNames(int page, String bookName, String bookName2, String token) {
        IPage<Book> iPage = new Page<>(page, 10);
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.like("name", bookName);
        wrapper.like("name", bookName2);
        List<Book> list = list(iPage, wrapper);
//        List<Book> books = checkExistsCart(list, token);
        iPage.setRecords(list);
        return ResultTool.success(iPage);
    }

    /**
     * 查询主页面四本低价书
     *
     * @param number
     * @return
     */
    @Override
    public JsonResult findLower(int number) {
        List<Book> lower = bookMapper.findLower(number);
        return ResultTool.success(lower);
    }

    /**
     * 查询所有的低价书
     *
     * @param page
     * @return
     */
    @Cacheable(cacheNames = "getLowerBook", key = "#page+'.'+#token")
    public JsonResult findLowerMore(int page, String token) {
        IPage<Book> iPage = new Page<>(page, 10);
        int start = (page - 1) * 10;
        List<Book> list = bookMapper.findLowerMore(start);
//        List<Book> books = checkExistsCart(list, token);
        iPage.setRecords(list);
        iPage.setTotal(bookMapper.findLowerMoreCount());
        return ResultTool.success(iPage);
    }


    /**
     * 二级查询低价书（按名称）
     *
     * @param page
     * @param bookname
     * @return
     */
    @Override
    public JsonResult findLowerAndBooknameMore(int page, String bookname, String token) {
        IPage<Book> iPage = new Page<>(page, 10);
        int start = (page - 1) * 10;
        List<Book> list = bookMapper.findLowerAndBooknameMore(start, '%' + bookname + '%');
//        List<Book> books = checkExistsCart(list, token);
        iPage.setRecords(list);
        iPage.setTotal(bookMapper.findLowerAndBooknameMoreCount('%' + bookname + '%'));
        return ResultTool.success(iPage);
    }

    /**
     * 二级搜索新鲜好书（按名称）
     *
     * @param page
     * @param bookName
     * @return
     */
    @Override
    public JsonResult findNewBookByNameAndTime(int page, String bookName, String token) {
        IPage<Book> iPage = new Page<>(page, 10);
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.like("name", bookName);
        wrapper.last("and create_time >(select DATE_ADD(now(),INTERVAL -3 day)) order by create_time desc");
        List<Book> list = list(wrapper);
//        List<Book> books = checkExistsCart(list, token);
        iPage.setRecords(list);
        return ResultTool.success(iPage);
    }

    /**
     * 标记购物车中的书是否购买
     *
     * @param list
     * @param token
     * @return
     */
//    public List<Book> checkExistsCart(List<Book> list, String token) {
//        log.info("checkExistsCart: {}", token);
//        boolean b = JwtConfig.checkToken(token);
//        log.info("b:{}",b);
//        if (!b) {
//            return list;
//        }
//        Claims claims = JwtConfig.parseJWT(token);
//        Object userId = claims.get("id");
//        log.info("userId:{}",userId);
//        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
//        String s = ops.get(UserServiceImpl.LOGIN_PREFIX + userId);
//        log.info("s: {}", s);
//        if (!Objects.equals(s, token)) {
//            return list;
//        }
//        log.info("获取用户购物车");
//        HashOperations<String, Object, Object> ops1 = stringRedisTemplate.opsForHash();
//        Map<Object, Object> entries = ops1.entries(ShoppingCartServiceImpl.SHOPPING_CART + userId);
//        for (Book book : list) {
//            boolean b1 = entries.containsKey(book.getId());
//            if (b1) {
//                book.setShow(Boolean.TRUE);
//            }
//            log.info("book: {}", book);
//        }
//
//        return list;
//    }
}
